require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/rvm'
#require 'mina/whenever'

environments = {
  'production' => {
    user: 'root',
    domain: '180.153.151.49',
    branch: 'master',
    deploy_to: "/var/app/luke/",
    rvm_path: '/usr/local/rvm/bin/rvm'
  }
}

rails_env = environments.keys.include?(ENV['RAILS_ENV']) ? ENV['RAILS_ENV'] : 'production'
branch = environments[rails_env][:branch]
domain = environments[rails_env][:domain]

set :rails_env, 'production'
set :domain, domain
set :deploy_to, environments[rails_env][:deploy_to]
set :repository, 'https://git.oschina.net/u2/luke.git'
set :branch, branch
set :ssh_options, '-A'

set :shared_paths, ['log', 'tmp/restart.txt', 'public/uploads','public/system', 'public/robots.txt', 'config/database.yml']

set :user, environments[rails_env][:user]
set :term_mode, :nil

set :rvm_path, environments[rails_env][:rvm_path]

task :environment do
  invoke :'rvm:use[ruby-2.1.1@default]'
end

task :setup => :environment do
  queue! %[mkdir -p "#{deploy_to}/shared/log"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/log"]

  queue! %[mkdir -p "#{deploy_to}/shared/tmp"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp"]

  queue! %[touch "#{deploy_to}/shared/tmp/restart.txt"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/restart.txt"]

  queue! %[mkdir -p "#{deploy_to}/shared/config"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/config"]

  queue! %[mkdir "#{deploy_to}/shared/public/uploads"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/uploads"]

  queue! %[mkdir "#{deploy_to}/shared/public/system"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/system"]

  queue! %[touch "#{deploy_to}/shared/public/robots.txt"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/robots.txt"]

  queue! %[touch "#{deploy_to}/shared/config/database.yml"]
  queue  %[echo "-----> Be sure to edit '#{deploy_to}/shared/config/database.yml'."]

end

desc "Deploys the current version to the server."
task :deploy => :environment do
  deploy do
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'

    to :launch do
      case ENV['RAILS_ENV']
      when 'production'
        queue "chmod a+w -R /var/app/luke/current/tmp"
      end
      queue "touch #{deploy_to}/#{current_path}/tmp/restart.txt"
    end
  end
end